﻿function InintCotrol() {
    layui.use(['autocomplete', 'laydate'], function () {        
        var laydate = layui.laydate;
        var autocomplete = layui.autocomplete;
        var dateCotrol = $(".mydate");
        if (dateCotrol.length > 0) {
            $.each(dateCotrol, function () {
                var controlID = $(this).prop("id");
                var type = $(this).attr("data-type");
                var format = $(this).attr("data-format");
                if (controlID != undefined && controlID != null) {
                    laydate.render({
                        elem: '#' + controlID,
                        type: type,
                        showBottom: false,//没有下方的取消和确定按钮
                        format: format,
                        change: function (value, date, endDate) {
                            $("#" + controlID).val(value);
                            if ($(".layui-laydate").length) {
                                $(".layui-laydate").remove();
                            }
                        }
                    });
                }
            });
        }
        var autocompleteCotrol = $(".autocomplete");
        if (autocompleteCotrol.length > 0) {
            $.each(autocompleteCotrol, function () {
                var controlID = $(this).prop("id");
                var url = $(this).attr("data-url");
                var type = $(this).attr("data-type");
                var name = $(this).attr("data-name");
                if (controlID != undefined && controlID != null) {
                    if (type == 1) {//单个引用
                        autocomplete.render({
                            elem: '#' + controlID,
                            url: url,
                            cache: false,
                            template_val: '{{d.JsonInfo}}',
                            template_txt: '{{d.Title}}',
                            onselect: function (resp) {
                                if (resp != null) {
                                    var obj = $("#" + controlID);
                                    obj.val(resp.Title);
                                    obj.parent().find(".mydata").val(resp.JsonInfo);
                                    obj.attr("title", "单据编号：" + resp.No);
                                }
                            }
                        });
                    }
                    else if (type == 2) {//多个引用
                        autocomplete.render({
                            elem: '#' + controlID,
                            url: url,
                            cache: false,
                            template_val: '{No:d.No,Title:d.Title,FormID:d.FormID,CustomID:d.CustomID}',
                            template_txt: '{{d.Title}}',
                            onselect: function (resp) {
                                $("#" + controlID).val("");
                                var trLength = $("." + controlID + "Table tbody").find("tr").length;
                                var indexStep = parseInt(trLength);
                                var nowRow = '<tr><td>' + resp.No + '<input type ="hidden" class="No" value="' + resp.No + '" name="' + name + '[' + trLength + '].No" /><input type ="hidden" class="FormID" value="' + resp.FormID + '" name="' + name + '[' + trLength + '].FormID" /><input type="hidden" class="ID" value="' + resp.CustomID + '" name="' + name + '[' + trLength + '].CustomID" /><input type ="hidden" class="Title" value="' + resp.Title + '" name="' + name + '[' + trLength + '].Title" /><input type ="hidden" class="Status" value="1" name="' + name + '[' + trLength + '].Status" /></td><td>' + resp.Title + '</td><td><span class="delete">删除</span></td></tr>';
                                $("." + controlID + "Table tbody").append(nowRow);
                            }
                        });
                    }
                    else if (type == 3) {
                        autocomplete.render({
                            elem: '#' + controlID,
                            url: url,
                            cache: false,
                            template_val: '{p:"{d.p}}",s:"{d.s}}",i:"{d.i}}",n:"{d.n}}",d:"{d.d}}",}',
                            template_txt: '{{d.n}} <span class=\'layui-badge layui-bg-gray\'>{{d.d}}&nbsp;{{d.s}}&nbsp;{{d.n}}</span>',
                            onselect: function (resp) {
                                $("#" + controlID).val("");
                                var trLength = $("." + controlID + "Table tbody").find("tr").length;
                                var indexStep = parseInt(trLength) + 1;
                                if ($("." + name + "_" + resp.i).length > 0) return;
                                $("." + controlID + "Table tbody").append('<tr  data-id="' + trLength + '" class="' + name + '_' + resp.i + '"><td><input type="hidden" class="Status" value="1" name="' + name + '[' + trLength + '].Status"/><input type="hidden" value="' + resp.p + '" name="' + name + '[' + trLength + '].PositionID" />' + resp.d + '</td><td><input type="hidden" value="' + resp.i + '" name="' + name + '[' + trLength + '].EmpID"/>' + resp.s + '</td><td>' + resp.n + '</td><td><span class="delete">删除</span></td></tr>');
                            }
                        });

                    }
                    else if (type == 4) {//职员选择 自定义流程
                        autocomplete.render({
                            elem: '#' + controlID,
                            url: url,
                            cache: false,
                            template_val: '{p:"{d.p}}",s:"{d.s}}",i:"{d.i}}",n:"{d.n}}",d:"{d.d}}",}',
                            template_txt: '{{d.n}} <span class=\'layui-badge layui-bg-gray\'>{{d.d}}&nbsp;{{d.s}}&nbsp;{{d.n}}</span>',
                            onselect: function (resp) {
                                $("#" + controlID).val("");
                                var trLength = $("." + controlID + "Table tbody").find("tr").length;
                                var indexStep = parseInt(trLength) + 1;
                                if ($("." + name + "_" + resp.i).length > 0) return;
                                $("." + controlID + "Table tbody").append('<tr  data-id="' + trLength + '" class="' + name + '_' + resp.i + '"><td><input type="hidden" class="Status" value="1" name="' + name + '[' + trLength + '].Status"/><input type="hidden" value="' + resp.p + '" name="' + name + '[' + trLength + '].PositionID" /><input type="hidden" value="' + resp.di + '" name="' + name + '[' + trLength + '].DepartmentID" /><input type="hidden" value="' + resp.d + '" name="' + name + '[' + trLength + '].DepatrmentName" /><input type="hidden" value="' + resp.s + '" name="' + name + '[' + trLength + '].PositionName" />' + resp.d + '</td><td><input type="hidden" value="' + resp.i + '" name="' + name + '[' + trLength + '].EmpID"/><input type="hidden" value="' + resp.n + '" name="' + name + '[' + trLength + '].EmpName"/>' + resp.s + '</td><td>' + resp.n + '</td><td><input type="text" class="layui-input" style="max-width:80px;" value="' + indexStep + '" name="' + name + '[' + trLength + '].Setp"/></td><td><span class="delete">删除</span></td></tr>');
                            }
                        });

                    }
                    else if (type == 5) {//产品 公司
                        autocomplete.render({
                            elem: '#' + controlID,
                            url: url,
                            cache: false,
                            template_val: '{{d.JsonInfo}}',
                            template_txt: '{{d.Name}}',
                            onselect: function (resp) {
                                if (resp != null) {
                                    var obj = $("#" + controlID);
                                    obj.val(resp.Name);
                                    obj.parent().find(".mydata").val(resp.JsonInfo);
                                    obj.attr("title", "编号：" + resp.ID);
                                    var attribute = obj.attr("myattribute");
                                    var parentObj = null;
                                    if (obj.parent().parent()[0].tagName == "TR") {
                                        parentObj = obj.parent().parent();
                                    }
                                    else {
                                        parentObj = obj.parent().parent().parent();
                                    }
                                    var myContact = parentObj.find(".Contact_" + attribute);
                                    if (myContact.length > 0) {
                                        $.get("/Member/Home/GetContactByCompanyID?id=" + resp.ID, function (result) {
                                            var items = "";
                                            $.each(result.List, function (index, item) {
                                                items += "<option value='" + item.Info + "'>" + item.Contacts + "<option>"
                                            });
                                            $.each(myContact, function () {
                                                $(this).html(items);
                                                var currentvalue = $(this).attr("currentvalue");
                                                $(this).val(currentvalue);
                                            });
                                            form.render();
                                        });

                                    }
                                }

                            }
                        });
                    }

                }
            });
        }
    });
}
function InintTable() {
    $(".xm-select-demo").each(function (index, item) {
        if ($(item).html() == "") {
            var base64Info = $(item).attr("data-values");
            var selects = $(item).attr("data-value");
            var tips = $(item).attr("data-tips");
            var my_id = $(item).prop("id");
            var str = Base64.decode(base64Info);
            var list = JSON.parse(str);
            var currentValues = [];
            if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
            var mydata = [];
            $.each(list, function (index, item) {
                if (currentValues != null && currentValues.length > 0 && currentValues.indexOf(item.Value) > -1) {
                    mydata.push({ name: item.Text, value: item.Value, selected: true });
                }
                else {
                    mydata.push({ name: item.Text, value: item.Value, selected: false });
                }
            });
            var my_name = $(item).attr("data-name");
            xmSelect.render({
                el: '#' + my_id,
                tips: tips,
                data: mydata,
                name: my_name,
                model: {
                    label: {
                        type: 'text',
                        block: {
                            showCount: 1,
                            showIcon: false,
                        }
                    }
                },
            })
        }
    });

    $(".xm-select-department").each(function (index, item) {
        if ($(item).html() == "") {
            var selects = $(item).attr("data-value");
            var currentValues = [];
            if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
            var tips = $(item).attr("data-tips");
            var my_id = $(item).prop("id");
            var my_name = $(item).attr("data-name");
            xmSelect.render({
                el: '#' + my_id,
                tips: tips,
                initValue: currentValues,
                data: xmSelectDepartment,
                filterable: true,
                radio: true,
                clickClose: true,
                name: my_name,
                tree: {
                    show: true,
                    showFolderIcon: true,
                    showLine: true,
                    indent: 20,
                    expandedKeys: true,
                    strict: false
                },
                model: {
                    label: {
                        type: 'text',
                        block: {
                            showCount: 1,
                            showIcon: false,
                        }
                    }
                },
            })
        }
    });

    $(".xm-select-employee").each(function (index, item) {
        if ($(item).html() == "") {
            var selects = $(item).attr("data-value");
            var currentValues = [];
            if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
            var tips = $(item).attr("data-tips");
            var my_id = $(item).prop("id");
            var my_name = $(item).attr("data-name");
            xmSelect.render({
                el: '#' + my_id,
                tips: tips,
                initValue: currentValues,
                data: xmSelectEmployee,
                name: my_name,
                filterable: true,
                radio: true,
                clickClose: true,
                tree: {
                    show: true,
                    showFolderIcon: true,
                    showLine: true,
                    indent: 20,
                    expandedKeys: true,
                    strict: true
                },
                model: {
                    label: {
                        type: 'text',
                        block: {
                            showCount: 1,
                            showIcon: false,
                        }
                    }
                },
            })
        }
    });

    $(".xm-select-position").each(function (index, item) {
        if ($(item).html() == "") {
            var selects = $(item).attr("data-value");
            var currentValues = [];
            if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
            var tips = $(item).attr("data-tips");
            var my_id = $(item).prop("id");
            var my_name = $(item).attr("data-name");
            xmSelect.render({
                el: '#' + my_id,
                tips: tips,
                initValue: currentValues,
                data: xmSelectPositions,
                name: my_name,
                filterable: true,
                radio: true,
                clickClose: true,
                tree: {
                    show: true,
                    showFolderIcon: true,
                    showLine: true,
                    indent: 20,
                    expandedKeys: true,
                    strict: true
                },
                model: {
                    label: {
                        type: 'text',
                        block: {
                            showCount: 1,
                            showIcon: false,
                        }
                    }
                },
            })
        }
    });

}
var tableRowTemplate = {};
var autocomplete, form, layer, laydate;
layui.use(['form', 'layedit', 'autocomplete', 'element', 'layer', 'laydate'], function () {
    form = layui.form;
    layer = layui.layer;
    element = layui.element;
    laydate = layui.laydate;
    autocomplete = layui.autocomplete;
    var inputType = [1, 2, 6, 8, 9, 10, 11, 12, 15, 16, 19, 20, 21, 68, 69, 81, 82, 83, 122, 123, 124, 135];
    var selectType = [3, 25];
    var radioType = [4];
    var checkboxType = [5, 7];
    var autocompleteType = [30, 40, 41, 42, 43];
    form.on('submit(OAForm2)', function (data) {
        console.log(123);
        $(".mytablecontent").each(function (index, item) {
            var attribute = $(item).attr("data-tableattribute");
            var list = [];
            $(item).find("tbody tr").each(function (trIndex, trItem) {
                var trInfo = {};
                $(trItem).find("td").each(function (tdIndex, tdItme) {

                    var tdttribute = $(tdItme).attr("data-attribute");
                    if (tdttribute != undefined) {
                        var type = parseInt($(tdItme).attr("data-type"));

                        var tdValue = "";
                        if (inputType.includes(type)) {
                            if ($(tdItme).find("input.layui-input").length > 0) {
                                tdValue = $(tdItme).find("input.layui-input").val();
                            }
                            else {
                                tdValue = $(tdItme).find("input").val();
                            }
                        }
                        else if (selectType.includes(type)) {

                            tdValue = $(tdItme).find("select").val();
                        }
                        else if (radioType.includes(type)) {
                            tdValue = $(tdItme).find('input:radio:checked').val();
                        }
                        else if (checkboxType.includes(type)) {
                            var vals = [];
                            $.each($(tdItme).find('input:checkbox:checked'), function () {
                                vals.push($(this).val());
                            });
                            tdValue = vals.join(',');
                        }
                        else if (autocompleteType.includes(type))
                        {
                            var tempValue = $(this).find(".mydata").val();
                            if (tempValue== "") {
                                tdValue = "";
                            }
                            else {
                                console.log(tempValue);
                                tdValue = Base64.decode(tempValue);
                            }                            
                        }
                        else if (type == 44)
                        {
                            var tempValue = $(tdItme).find("select").val();
                            if (tempValue == "") {
                                tdValue = "";
                            }
                            else {
                                console.log(tempValue);
                                tdValue = Base64.decode(tempValue);
                            }
                        }
                        else {
                            console.log(type + "未设置值接收");
                        }
                        trInfo[tdttribute] = tdValue;
                    }

                });
                list.push(trInfo);
            });
            console.log(JSON.stringify(list));//dicExtend__E
            $("#dicExtend_" + attribute).val(JSON.stringify(list));
        })
        $(".mySubmit").prop("disabled", true);
        var index = layer.load(1, {
            shade: [0.1, '#fff']
        });
        var myFrom = $("#myForm");
        $.post(myFrom.prop("action"), $("#myForm").serialize(), function (result) {
            $(".mySubmit").prop("disabled", false);
            layer.closeAll();
            if (result.State == 400) {
                layer.msg(result.Msg);
                return;
            }
            if (result.State == 402) {
                layer.msg(result.Msg);
                return;
            }
            else {
                if (result.Msg.startsWith("url:")) {
                    window.location.href = result.Msg.substring(4);
                }
                else {
                    layer.msg(result.Msg);
                    if (parentUrl != "") {
                        setTimeout(function () { window.parent.href = parentUrl; }, 1000);
                    }
                    else if (currentUrl != "") {
                        window.location.href = currentUrl;
                    }
                    else {
                        window.parent.RefreshResultList();
                    }
                }

            }
        });
        return false;
    });
    InintCotrol();
    InintTable();
});
Math.formatFloat = function (f, digit) {
    var m = Math.pow(10, digit);
    return Math.round(f * m, 10) / m;
}
function automaticCalculation(e, obj) {
    var value = e.delegateTarget.value;
    var calculations_68 = $(obj).parent().parent().find(".item_68");
    var calculations_69 = $(obj).parent().parent().find(".item_69");
    var _21Values = {};
    $(obj).parent().parent().find(".item_21").each(function (index, item) {

        var attr = $(item).attr("data-attribute");
        var value = $(item).find("input").val();
        if (value == "") value = "0";
        _21Values[attr] = value;
    });
    if (calculations_68.length > 0) {
        calculations_68.each(function (index, item) {
            var formulas = $(this).attr("data-values");
            $.each(_21Values, function (key, value) {
                formulas = formulas.replaceAll(key, value);
            })
            $(item).find("input").val(Math.formatFloat(formulas, 2));
        });
    }
    if (calculations_69.length > 0) {
        calculations_69.each(function (index, item) {
            var formulas = $(this).attr("data-values");
            $.each(_21Values, function (key, value) {
                formulas = formulas.replaceAll(key, value);

            })
            $(item).find("input").val(Math.formatFloat(eval(formulas), 2));
        });
    }
}

$(document).on("click", ".addItem", function () {

    var my_tbody = $(this).parent().parent().parent().parent().find("tbody");
    var last = my_tbody.find("tr:last");
    var lastID = last.attr("data-id");
    var currentIndex = parseInt(lastID) + 1;
    var tableattribute = $(this).parent().parent().parent().parent().attr("data-tableattribute");
    var outerHTML = "<tr data-id='" + currentIndex + "'>" + tableRowTemplate[tableattribute] + "</tr>";
    //var outerHTML = last.prop('outerHTML');
    var reg = new RegExp("\\[0\\]", "g");
    var reg2 = new RegExp("_0_", "g");
    var reg3 = new RegExp("lay-key=\"\\d+\"", "g");
    outerHTML = outerHTML.replace('data-id="0"', 'data-id="' + currentIndex + '"');
    outerHTML = outerHTML.replace(reg, "[" + currentIndex + "]");
    outerHTML = outerHTML.replace(reg2, "_" + currentIndex + "_");
    outerHTML = outerHTML.replace(reg3, "");

    //layui-form-checkbox    layui-form-switch  layui-form-radio
    var checkboxRegex = new RegExp("<div[^>]+ layui-form-checkbox[^>]+>[\s\S]*?</i></div>", "gmi");
    var radioRegex = new RegExp("<div[^>]+ layui-form-radio[^>]+>[\s\S]*?</div></div>", "gmi");
    var switchRegex = new RegExp("<div[^>]+ layui-form-switch[^>]+>[\s\S]*?</i></div>", "gmi");
    outerHTML = outerHTML.replace(checkboxRegex, "");
    outerHTML = outerHTML.replace(radioRegex, "");
    outerHTML = outerHTML.replace(switchRegex, "");
    //console.log(outerHTML);
    my_tbody.append(outerHTML);
    my_tbody.find("tr:last").find("input.layui-input").val("");
    my_tbody.find("tr:last").css("display", "");
    layui.use('form', function () {
        var form = layui.form;
        form.render();
    });
    $(".webuploader-pick").html("选择文件");
    InintCotrol();
    InintTable();

});
$(document).on("click", ".delete", function () {
    $(this).parent().parent().find("input").addClass(".isHidden").removeClass("mydate");
    $(this).parent().parent().find("input").val("0");
    $(this).parent().parent().find(".Status").val("-1");
    $(this).parent().parent().find("input").removeAttr("lay-verify");
    $(this).parent().parent().css("display", "none");
});
$(document).on("click", ".deleteItem", function () {
    $(this).parent().parent().remove();
});
$(".addCondition").click(function () {
    var my_tbody = $(this).parent().parent().parent().parent().find("tbody");
    var last = my_tbody.find("tr:last");
    var lastID = last.attr("data-id");
    var currentIndex = parseInt(lastID) + 1;
    var outerHTML = last.prop('outerHTML');
    var reg = new RegExp("\\[" + lastID + "\\]", "g");
    var reg2 = new RegExp("_" + lastID + "_", "g");
    outerHTML = outerHTML.replace('data-id="' + lastID + '"', 'data-id="' + currentIndex + '"');
    outerHTML = outerHTML.replace(reg, "[" + currentIndex + "]");
    outerHTML = outerHTML.replace(reg2, "_" + currentIndex + "_");
    my_tbody.append(outerHTML);

    my_tbody.find("tr:last").css("display", "");
    layui.use('form', function () {
        var form = layui.form;
        form.render();
    });
});

